/** dev server @author dongls */
process.env.NODE_ENV = 'development'

const koaWebpack = require('publink-koa-webpack')
const colors = require('colors')

const Koa = require('koa');
const koaStatic = require('koa-static');
const app = new Koa()

const { historyApiFallback } = require('koa2-connect-history-api-fallback');

const { exec } = require('child_process')

const webpackDevConfig = require('../config/webpack.spa.dev.conf')

const koaConnect = require('koa-connect')

const path = require('path')

const { createProxyMiddleware } = require('http-proxy-middleware')

const bodyParser = require("koa-bodyparser");

import nodeProxyConfig, { localeRunPort } from '../server/util/NodeProxyConfig.js'
const { port:proxyPort, headerSign } = nodeProxyConfig;

const koaWebpackConfig = {
  config: webpackDevConfig,
  devMiddleware: {
    watchOptions: {
      // The default
      aggregateTimeout: 1500,
      ignored: ['dist', 'public', 'node_modules', 'script', 'server', 'cli', 'config']
    }
  },
  // IE11对websocket报SecurityError
  // 解决方案： Internet选项->安全->本地Internet->站点，把所有勾选取消
  hotClient: false
}



app.use(historyApiFallback());

/**
 * @description: 启动
 * @return {void}
 */
function start() {
  koaWebpack(koaWebpackConfig).then(middleware => {
    middleware.devMiddleware.waitUntilValid(() => {
      app.use(middleware)
      
      app.use(async (ctx, next) => {
        if (ctx.url.startsWith('/serve/')) {
          ctx.respond = false;
          await koaConnect(
            createProxyMiddleware({
              target: `http://localhost:${proxyPort}`,
              changeOrigin: true
            })
          )(ctx, next);
        }
        await next();
      });

      app.use(bodyParser());

      app.use(
        koaStatic(path.resolve(__dirname, '../public'), { index: '_index.html' })
      );
      
      // 启动server  outputs green text
      app.listen(localeRunPort, ()=> {
        const LISTEN_ADDRESSS = `http://127.0.0.1:${localeRunPort}`
        console.log(`${colors.bgGreen('[本地地址]:') } ${LISTEN_ADDRESSS}`)
        process.platform === 'darwin' ? exec(`open  ${LISTEN_ADDRESSS}`) : exec(`start  ${LISTEN_ADDRESSS}`)
      })
    })
  })
}

start()